<template>
  <div class="exam-details">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试详情</span>
          <div class="header-actions">
            <el-select 
              v-model="selectedExam" 
              placeholder="选择考试" 
              @change="loadExamDetails"
              style="width: 200px"
            >
              <el-option
                v-for="exam in exams"
                :key="exam.id"
                :label="exam.name"
                :value="exam.id"
              >
                <span>{{ exam.name }}</span>
              </el-option>
            </el-select>
            <el-button type="primary" @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="selectedExamDetails" class="exam-content">
        <div class="exam-info">
          <h3>{{ selectedExamDetails.name }}</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">考试时间：</span>
              <span class="value">{{ selectedExamDetails.startTime }} - {{ selectedExamDetails.endTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">考试时长：</span>
              <span class="value">{{ selectedExamDetails.duration }}</span>
            </div>
            <div class="info-item">
              <span class="label">总分：</span>
              <span class="value">{{ selectedExamDetails.totalScore }}分</span>
            </div>
            <div class="info-item">
              <span class="label">及格分数：</span>
              <span class="value">{{ selectedExamDetails.passScore }}分</span>
            </div>
            <div class="info-item">
              <span class="label">考试状态：</span>
              <el-tag :type="getExamStatusType(selectedExamDetails.status)">
                {{ getExamStatusText(selectedExamDetails.status) }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">考试说明：</span>
              <span class="value">{{ selectedExamDetails.description }}</span>
            </div>
          </div>
        </div>

        <el-divider />

        <div class="score-details">
          <div class="section-header">
            <h4>成绩详情</h4>
            <el-button type="primary" size="small" @click="exportScoreDetails">
              <el-icon><Download /></el-icon>
              导出成绩
            </el-button>
          </div>
          <el-table :data="selectedExamDetails.scores" style="width: 100%" stripe>
            <el-table-column prop="subject" label="科目" />
            <el-table-column prop="score" label="得分">
              <template #default="{ row }">
                <span :class="getScoreClass(row.score, row.passScore)">
                  {{ row.score }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="rank" label="排名">
              <template #default="{ row }">
                <el-tag :type="getRankType(row.rank)">
                  {{ row.rank }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="average" label="平均分" />
            <el-table-column prop="highest" label="最高分" />
            <el-table-column prop="lowest" label="最低分" />
            <el-table-column prop="passRate" label="及格率">
              <template #default="{ row }">
                <el-progress :percentage="row.passRate" :status="getPassRateStatus(row.passRate)" />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-divider />

        <div class="score-trend">
          <div class="section-header">
            <h4>成绩趋势</h4>
            <el-radio-group v-model="trendType" size="small">
              <el-radio-button value="line">折线图</el-radio-button>
              <el-radio-button value="bar">柱状图</el-radio-button>
            </el-radio-group>
          </div>
          <div id="score-trend-chart" style="width: 100%; height: 300px;"></div>
        </div>

        <el-divider />

        <div class="answer-analysis">
          <div class="section-header">
            <h4>答题分析</h4>
            <el-button type="primary" size="small" @click="showAnswerDetails">
              <el-icon><View /></el-icon>
              查看答题详情
            </el-button>
          </div>
          <el-table :data="selectedExamDetails.analysis" style="width: 100%" stripe>
            <el-table-column prop="questionType" label="题型" />
            <el-table-column prop="correctCount" label="正确题数" />
            <el-table-column prop="totalCount" label="总题数" />
            <el-table-column prop="accuracy" label="正确率">
              <template #default="{ row }">
                <el-progress :percentage="parseFloat(row.accuracy)" :status="getAccuracyStatus(row.accuracy)" />
              </template>
            </el-table-column>
            <el-table-column prop="timeSpent" label="平均用时" />
            <el-table-column prop="difficulty" label="难度">
              <template #default="{ row }">
                <el-rate
                  v-model="row.difficulty"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-divider />

        <div class="knowledge-analysis">
          <div class="section-header">
            <h4>知识点分析</h4>
            <el-button type="primary" size="small" @click="showKnowledgeDetails">
              <el-icon><Document /></el-icon>
              查看知识点详情
            </el-button>
          </div>
          <el-table :data="selectedExamDetails.knowledgePoints" style="width: 100%" stripe>
            <el-table-column prop="name" label="知识点" />
            <el-table-column prop="score" label="得分" />
            <el-table-column prop="total" label="总分" />
            <el-table-column prop="mastery" label="掌握程度">
              <template #default="{ row }">
                <el-progress :percentage="row.mastery" :status="getMasteryStatus(row.mastery)" />
              </template>
            </el-table-column>
            <el-table-column prop="suggestions" label="学习建议" show-overflow-tooltip />
          </el-table>
        </div>
      </div>

      <el-empty v-else description="请选择考试查看详情" />
    </el-card>

    <!-- 答题详情对话框 -->
    <el-dialog
      v-model="answerDialogVisible"
      title="答题详情"
      width="70%"
    >
      <div v-if="selectedAnswerDetails" class="answer-details">
        <el-tabs v-model="activeAnswerTab">
          <el-tab-pane label="答题记录" name="record">
            <el-table :data="selectedAnswerDetails.records" style="width: 100%">
              <el-table-column prop="questionNo" label="题号" width="80" />
              <el-table-column prop="content" label="题目内容" show-overflow-tooltip />
              <el-table-column prop="yourAnswer" label="你的答案" />
              <el-table-column prop="correctAnswer" label="正确答案" />
              <el-table-column prop="score" label="得分" width="80" />
              <el-table-column prop="timeSpent" label="用时" width="100" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="错题分析" name="analysis">
            <div class="wrong-questions">
              <div v-for="(question, index) in selectedAnswerDetails.wrongQuestions" :key="index" class="wrong-question">
                <h5>第{{ question.questionNo }}题</h5>
                <p class="question-content">{{ question.content }}</p>
                <p class="your-answer">你的答案：{{ question.yourAnswer }}</p>
                <p class="correct-answer">正确答案：{{ question.correctAnswer }}</p>
                <p class="analysis">解析：{{ question.analysis }}</p>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 知识点详情对话框 -->
    <el-dialog
      v-model="knowledgeDialogVisible"
      title="知识点详情"
      width="70%"
    >
      <div v-if="selectedKnowledgeDetails" class="knowledge-details">
        <el-tabs v-model="activeKnowledgeTab">
          <el-tab-pane label="知识点掌握情况" name="mastery">
            <div class="mastery-chart" style="width: 100%; height: 400px;"></div>
          </el-tab-pane>
          <el-tab-pane label="学习建议" name="suggestions">
            <div class="suggestions-list">
              <el-timeline>
                <el-timeline-item
                  v-for="(suggestion, index) in selectedKnowledgeDetails.suggestions"
                  :key="index"
                  :timestamp="suggestion.time"
                  :type="suggestion.type"
                >
                  {{ suggestion.content }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { Refresh, Download, View, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Exam {
  id: string
  name: string
  startTime: string
  endTime: string
  duration: string
  totalScore: number
  passScore: number
  status: 'upcoming' | 'ongoing' | 'ended'
  description: string
  scores: Score[]
  analysis: Analysis[]
  knowledgePoints: KnowledgePoint[]
}

interface Score {
  subject: string
  score: number
  rank: number
  average: number
  highest: number
  lowest: number
  passScore: number
  passRate: number
}

interface Analysis {
  questionType: string
  correctCount: number
  totalCount: number
  accuracy: string
  timeSpent: string
  difficulty: number
}

interface KnowledgePoint {
  name: string
  score: number
  total: number
  mastery: number
  suggestions: string
}

interface AnswerDetails {
  records: AnswerRecord[]
  wrongQuestions: WrongQuestion[]
}

interface AnswerRecord {
  questionNo: number
  content: string
  yourAnswer: string
  correctAnswer: string
  score: number
  timeSpent: string
}

interface WrongQuestion {
  questionNo: number
  content: string
  yourAnswer: string
  correctAnswer: string
  analysis: string
}

interface KnowledgeDetails {
  mastery: any
  suggestions: Suggestion[]
}

interface Suggestion {
  time: string
  type: 'success' | 'warning' | 'info'
  content: string
}

const exams = ref<{ id: string; name: string }[]>([])
const selectedExam = ref('')
const selectedExamDetails = ref<Exam | null>(null)
const loading = ref(false)
const trendType = ref('line')
const answerDialogVisible = ref(false)
const knowledgeDialogVisible = ref(false)
const activeAnswerTab = ref('record')
const activeKnowledgeTab = ref('mastery')
const selectedAnswerDetails = ref<AnswerDetails | null>(null)
const selectedKnowledgeDetails = ref<KnowledgeDetails | null>(null)
let scoreTrendChart: echarts.ECharts | null = null
let masteryChart: echarts.ECharts | null = null

onMounted(() => {
  loadExams()
})

onUnmounted(() => {
  if (scoreTrendChart) {
    scoreTrendChart.dispose()
  }
  if (masteryChart) {
    masteryChart.dispose()
  }
})

watch(trendType, () => {
  initScoreTrendChart()
})

const loadExams = async () => {
  try {
    loading.value = true
    // 模拟API调用
    exams.value = [
      { id: '1', name: '期中考试' },
      { id: '2', name: '期末考试' }
    ]
  } catch (error) {
    ElMessage.error('加载考试列表失败')
  } finally {
    loading.value = false
  }
}

const loadExamDetails = async (examId: string) => {
  try {
    loading.value = true
    // 模拟API调用
    selectedExamDetails.value = {
      id: examId,
      name: '期中考试',
      startTime: '2024-04-20 09:00',
      endTime: '2024-04-20 11:00',
      duration: '120分钟',
      totalScore: 100,
      passScore: 60,
      status: 'ended',
      description: '本次考试主要考察学生对基础知识的掌握程度和应用能力。',
      scores: [
        {
          subject: '数学',
          score: 85,
          rank: 10,
          average: 75,
          highest: 98,
          lowest: 45,
          passScore: 60,
          passRate: 85
        },
        {
          subject: '英语',
          score: 90,
          rank: 5,
          average: 80,
          highest: 95,
          lowest: 50,
          passScore: 60,
          passRate: 90
        }
      ],
      analysis: [
        {
          questionType: '选择题',
          correctCount: 8,
          totalCount: 10,
          accuracy: '80%',
          timeSpent: '30分钟',
          difficulty: 3
        },
        {
          questionType: '填空题',
          correctCount: 6,
          totalCount: 8,
          accuracy: '75%',
          timeSpent: '45分钟',
          difficulty: 4
        }
      ],
      knowledgePoints: [
        {
          name: '函数与导数',
          score: 35,
          total: 40,
          mastery: 88,
          suggestions: '建议加强导数应用题的练习'
        },
        {
          name: '三角函数',
          score: 30,
          total: 35,
          mastery: 86,
          suggestions: '需要巩固三角函数的图像和性质'
        }
      ]
    }
    initScoreTrendChart()
  } catch (error) {
    ElMessage.error('加载考试详情失败')
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  if (selectedExam.value) {
    loadExamDetails(selectedExam.value)
  }
}

const initScoreTrendChart = () => {
  if (!selectedExamDetails.value) return

  const chartDom = document.getElementById('score-trend-chart')
  if (!chartDom) return

  // 如果已存在图表实例，先销毁
  if (scoreTrendChart) {
    scoreTrendChart.dispose()
  }

  scoreTrendChart = echarts.init(chartDom)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['个人成绩', '班级平均分']
    },
    xAxis: {
      type: 'category',
      data: selectedExamDetails.value.scores.map(score => score.subject)
    },
    yAxis: {
      type: 'value',
      name: '分数'
    },
    series: [
      {
        name: '个人成绩',
        type: trendType.value,
        data: selectedExamDetails.value.scores.map(score => score.score),
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '班级平均分',
        type: trendType.value,
        data: selectedExamDetails.value.scores.map(score => score.average),
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }

  scoreTrendChart.setOption(option)
}

const getExamStatusType = (status: string) => {
  switch (status) {
    case 'upcoming':
      return 'info'
    case 'ongoing':
      return 'success'
    case 'ended':
      return 'warning'
    default:
      return 'info'
  }
}

const getExamStatusText = (status: string) => {
  switch (status) {
    case 'upcoming':
      return '未开始'
    case 'ongoing':
      return '进行中'
    case 'ended':
      return '已结束'
    default:
      return '未知'
  }
}

const getScoreClass = (score: number, passScore: number) => {
  if (score >= passScore) return 'score-pass'
  return 'score-fail'
}

const getRankType = (rank: number) => {
  if (rank <= 3) return 'success'
  if (rank <= 10) return 'warning'
  return 'info'
}

const getPassRateStatus = (rate: number) => {
  if (rate >= 90) return 'success'
  if (rate >= 70) return 'warning'
  return 'exception'
}

const getAccuracyStatus = (accuracy: string) => {
  const rate = parseFloat(accuracy)
  if (rate >= 90) return 'success'
  if (rate >= 70) return 'warning'
  return 'exception'
}

const getMasteryStatus = (mastery: number) => {
  if (mastery >= 90) return 'success'
  if (mastery >= 70) return 'warning'
  return 'exception'
}

const exportScoreDetails = () => {
  // 实现导出成绩功能
  ElMessage.success('成绩导出成功')
}

const showAnswerDetails = () => {
  // 模拟加载答题详情
  selectedAnswerDetails.value = {
    records: [
      {
        questionNo: 1,
        content: '题目内容1',
        yourAnswer: 'A',
        correctAnswer: 'A',
        score: 5,
        timeSpent: '2分钟'
      },
      {
        questionNo: 2,
        content: '题目内容2',
        yourAnswer: 'B',
        correctAnswer: 'C',
        score: 0,
        timeSpent: '3分钟'
      }
    ],
    wrongQuestions: [
      {
        questionNo: 2,
        content: '题目内容2',
        yourAnswer: 'B',
        correctAnswer: 'C',
        analysis: '本题考查的是...'
      }
    ]
  }
  answerDialogVisible.value = true
}

const showKnowledgeDetails = () => {
  // 模拟加载知识点详情
  selectedKnowledgeDetails.value = {
    mastery: null,
    suggestions: [
      {
        time: '2024-04-21',
        type: 'success',
        content: '完成函数与导数的专项练习'
      },
      {
        time: '2024-04-22',
        type: 'warning',
        content: '需要加强三角函数的应用能力'
      }
    ]
  }
  knowledgeDialogVisible.value = true
  // 初始化知识点掌握情况图表
  nextTick(() => {
    initMasteryChart()
  })
}

const initMasteryChart = () => {
  const chartDom = document.querySelector('.mastery-chart')
  if (!chartDom) return

  // 如果已存在图表实例，先销毁
  if (masteryChart) {
    masteryChart.dispose()
  }

  masteryChart = echarts.init(chartDom as HTMLElement)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '知识点掌握情况',
        type: 'pie',
        radius: '50%',
        data: selectedExamDetails.value?.knowledgePoints.map(point => ({
          name: point.name,
          value: point.mastery
        })) || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  masteryChart.setOption(option)
}

// 监听知识点详情弹窗的打开状态
watch(knowledgeDialogVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initMasteryChart()
    })
  }
})
</script>

<style scoped>
.exam-details {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.exam-content {
  padding: 20px 0;
}

.exam-info {
  margin-bottom: 20px;
}

.exam-info h3 {
  margin-bottom: 15px;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  color: #606266;
  margin-right: 10px;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

h4 {
  margin: 0;
  color: #303133;
}

.score-pass {
  color: #67C23A;
  font-weight: bold;
}

.score-fail {
  color: #F56C6C;
  font-weight: bold;
}

.answer-details {
  padding: 20px 0;
}

.wrong-questions {
  padding: 20px;
}

.wrong-question {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.wrong-question h5 {
  margin: 0 0 10px 0;
  color: #303133;
}

.question-content {
  margin: 10px 0;
  color: #606266;
}

.your-answer {
  color: #F56C6C;
  margin: 5px 0;
}

.correct-answer {
  color: #67C23A;
  margin: 5px 0;
}

.analysis {
  color: #606266;
  margin: 10px 0 0 0;
}

.knowledge-details {
  padding: 20px 0;
}

.suggestions-list {
  padding: 20px;
}
</style> 